package com.xlh.aop;

import com.google.common.collect.Lists;
import com.xlh.exception.common.BadRequestException;
import com.xlh.exception.common.GlobalException;
import com.xlh.service.course.CourseService;
import com.xlh.util.AnnotationResolver;
import org.apache.commons.collections.MapUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 学生是否某课程正在考试
 * <p>
 * Created by lx on 2019/1/25.
 */
@Aspect
@Component
public class StudentCourseTestingAspect {

    @Autowired
    private CourseService courseService;

    @Before("@annotation(CourseTesting)")
    public void isStudentTesting(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        CourseTesting courseTesting = method.getAnnotation(CourseTesting.class);

        String key = AnnotationResolver.resolver(joinPoint, courseTesting.key());

        try {

            // 学生是否考试
            Map<Long, Boolean> studentIsTestingMap = courseService.getStudentIsTesting(
                    Lists.newArrayList(Long.valueOf(key)));

            if (MapUtils.isNotEmpty(studentIsTestingMap) && studentIsTestingMap.get(Long.valueOf(key))) {
                throw new GlobalException("当前课程正在考试，无法查看资源信息");
            }

        } catch (NumberFormatException e) {
            throw new BadRequestException();
        }

    }

}
